<template>
  <form-create :rule="rule" v-model="fApi" :option="option" :value.sync="formData" />
</template>
<script>
export default {
  name: "EvBuilder",
  props: {
    // 布局模型id
    layoutModelId: {
      type: String,
      default: "",
    },
    // 布局模型code
    layoutModelCode: {
      type: String,
      default: "",
    },
  },
  data() {
    return {
      formData: {},
      fApi: {},
      rule: [],
      option: {},
    };
  },
  mounted() {
    if (this.layoutModelCode) {
      this.getFormJsonByCode(this.layoutModelCode);
    } else if (this.layoutModelId) {
      this.getFormJsonById(this.layoutModelId);
    }
  },
  methods: {
    // 通过field获取Formily实例
    getInstance(field) {
      return this.fApi.el(field);
    },
    // 通过组件那么获取Formily实例
    getFormilyInstance(name) {
      return this.fApi.el(name)?.getInstance();
    },
    // 获取form表单值
    getValues() {
      const data = this.getFomilyData();
      return {
        ...this.formData,
        ...data,
      };
    },
    // 获取所有Formily组件的值
    getFomilyData() {
      let data = {};
      this.rule.forEach((item) => {
        if (item.type === "Formily") {
          const instance = this.getFormilyInstance(item.name);
          data[item.field] = instance.form.values;
        }
      });
      return data;
    },
    // 给指定field的Fromily组件设置值
    setValues(field, data) {
      const instance = this.getInstance(field)?.getInstance();
      if (instance) {
        instance.form.setValues(data);
      } else {
        console.log("未查找到对应" + field + "的组件");
      }
    },
    getFormJsonByCode(code) {
      const condition = { AND: [["code", "=", code]] };
      this.$server()
        .query("function-quality", "JsonFormData", condition, null, null, true)
        .then((res) => {
          if (res.total === 0) {
            this.$message.error("布局模型不存在，请检查！");
          } else {
            this.initBuilder(res.list[0]);
          }

          if (res.total > 1) {
            console.error("布局模型编码重复，请检查！");
          }
        })
        .catch((response) => {
          this.$message.error(response.data.message);
        });
    },
    getFormJsonById(id) {
      this.$server()
        .getObjectById("function-quality", "JsonFormData", id)
        .then((result) => {
          if (result) {
            this.initBuilder(result);
          }
        })
        .catch((response) => {
          this.$message.error(response.data.message);
        });
    },
    initBuilder(data) {
      this.option = JSON.parse(data.formData);
      this.rule = JSON.parse(data.jsonData);
      this.$nextTick(() => {
        this.$emit("ready", this.rule);
      });
    },
  },
};
</script>